#include <stdio.h>
#include "esp_lyn_wifi.h"
#include "esp_lyn_mqtt.h"
#include "esp_log.h"
#include "string.h"

#define TAG "main"

static void lyn_mqtt_listener(lyn_mqtt_state_t state, void *arg)
{
    switch (state)
    {
    case MQTT_STATE_CONNECTED:
        ESP_LOGI(TAG, "MQTT连接成功");
        int res = subscribe_lyn_topic("test", 2);
        ESP_LOGI(TAG, "MQTT订阅结果 %d", res);
        break;
    case MQTT_STATE_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT连接断开");
        break;
    case MQTT_STATE_INIT:
        ESP_LOGI(TAG, "MQTT初始化");
        break;
    case MQTT_STATE_CONNECTING:
        ESP_LOGI(TAG, "MQTT连接中");
        break;
    case MQTT_STATE_CONNECT_FAILED:
        ESP_LOGI(TAG, "MQTT连接失败");
        break;
    case MQTT_STATE_SUBSCRIBE_FAILED:
        ESP_LOGI(TAG, "MQTT订阅失败");
        break;
    case MQTT_STATE_SUBSCRIBE_SUCCESS:
        ESP_LOGI(TAG, "MQTT订阅成功");
        break;
    case MQTT_STATE_PUBLISH_FAILED:
        ESP_LOGI(TAG, "MQTT发布失败");
        break;
    case MQTT_STATE_DATA:
        char *data = (char *)arg;
        ESP_LOGI(TAG, "MQTT收到数据 %s\n", data);            
        break;
    }
}

static void lyn_wifi_listener(lyn_wifi_state_t state, void *org)
{
    switch (state)
    {
    case WIFI_STATE_INIT:
        ESP_LOGI(TAG, "WIFI初始化");
        break;
    case WIFI_STATE_CONNECTED:
        ESP_LOGI(TAG, "WIFI连接成功 IP地址 %s", (char *)org);
        lyn_mqtt_start("mqtt://a.kefaface.com", 1883, "abc124124", "", "", lyn_mqtt_listener);
        break;
    case WIFI_STATE_DISCONNECTED:
        ESP_LOGI(TAG, "WIFI连接断开");
        break;
    default:
        break;
    }
}

void app_main(void)
{
    lyn_wifi_init("longyn", "12345678", lyn_wifi_listener);
}